<template>
  <el-dialog
    v-model="visible"
    :title="$t('sysManagement.modify')"
    :close-on-click-modal="false"
    width="550px"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="auto"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('distribUserWallet.withdrawalAmount')"
        prop="settledAmount"
      >
        <el-input
          v-model="dataForm.settledAmount"
          type="number"
          oninput="if(value.length>13)value=value.slice(0,13)"
          @change="(value)=>{if(value>9999999999.99)$nextTick(()=>{dataForm.settledAmount = 9999999999.99})}"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('remindPop.cancel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('remindPop.confirm') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import Big from 'big.js'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshDataList'])
const validateNumber = (rule, value, callback) => {
  if (!/^[0-9]\d*$|^[0-9]\d*\.\d\d?$|^0\.\d\d?$/.test(value)) {
    callback(new Error($t('distribUserWallet.amountTips')))
  } else {
    callback()
  }
}
const dataRule = {
  settledAmount: [{ validator: validateNumber, trigger: 'blur' }],
  addupAmount: [{ validator: validateNumber, trigger: 'blur' }]
}

const dataForm = ref({
  walletId: null,
  distributionUserId: null,
  settledAmount: null,
  addupAmount: null,
  version: null
})
let rawAmount = null
const isSubmit = ref(true)
const visible = ref(false)
const init = (walletData) => {
  dataForm.value = Object.assign({}, walletData)
  rawAmount = walletData.settledAmount
  visible.value = true
  isSubmit.value = true
}
defineExpose({ init })

const dataFormRef = ref(null)
/**
 * 表单提交
 */
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid && isSubmit) {
      isSubmit.value = false
      dataForm.value.changeAmount = parseFloat(new Big(dataForm.value.settledAmount).minus(rawAmount))
      http({
        url: http.adornUrl('/distribution/distributionUserWallet'),
        method: 'put',
        data: http.adornData(dataForm.value)
      }).then(() => {
        ElMessage({
          message: $t('remindPop.success'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      })
    }
  })
}
</script>
